// UserServiceImpl.java
package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.Member;
import com.chixing.entity.User;
import com.chixing.mapper.UserMapper;
import com.chixing.service.IMemberService;
import com.chixing.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private IMemberService memberService;

    @Override
    public User getUserByPhone(String phone) {
        return getOne(new QueryWrapper<User>().eq("phone", phone));
    }

    @Override
    @Transactional// 事务控制
    public boolean register(User user) {
        user.setUserId(null);

        // 检查手机号是否已注册
        User existingUser = getOne(new QueryWrapper<User>().eq("phone", user.getPhone()));
        if (existingUser != null) {
            return false;
        }
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置注册时间
        user.setRegisterTime(java.time.LocalDateTime.now());
        user.setStatues(1); // 正常状态
        // 保存用户
        save(user);

        // ⭐ 获取刚插入的 userId（MyBatis-Plus 已自动回填）
        Integer userId = user.getUserId();

        // ====== 创建会员记录 ======
        Member member = new Member();
        member.setUserId(userId);
        member.setMemberAccount("user" + userId); // 自动生成会员账号
        member.setMemberLevel("青铜");             // 默认等级
        member.setMembershipPoints(0.0);          // 初始积分为0
        member.setCreateTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());
        member.setStatues(1);                     // 启用
        member.setVersion(1);

        // 保存会员
        memberService.save(member);
        return true;
    }

    @Override
    public void resetUserPassword(String phone, String newPassword) {
        User user = getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user != null) {
            // 使用 BCryptPasswordEncoder 加密密码
            user.setPassword(passwordEncoder.encode(newPassword));
            updateById(user);
        }
    }


    @Override
    public String login(String phone, String password) {
        // 查询用户
        User user = getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            return null; // 用户不存在
        }
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return null; // 密码错误
        }
        // 生成JWT
        return jwtUtils.generateToken(user.getUserId());
    }
}
